package com.yanqu.road.server.handle;

import com.yanqu.road.NettyMgr;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.server.connect.CrossAgentLinkedControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.task.CrossCommandTask;
import com.yanqu.road.utils.CommandUtils;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Sharable
public class CrossServerHandler extends SimpleChannelInboundHandler<YanQuMessage> {

    private static Logger logger = LogManager.getLogger(CrossServerHandler.class.getName());
    private String handlerName;

    public CrossServerHandler() {
        handlerName = "crossServer handler";
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("receive a connect: {} " , ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("connection disconnected : " + ctx.channel().remoteAddress());
        ServerConnectionGroup connectionGroup = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
        if (null != connectionGroup) {
            CrossAgentLinkedControl.closeConnection(ctx);
            logger.error(toMessage(
                    "close the connection to agent disconnected. connection : " + ctx.channel().remoteAddress()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("connect error : " + ctx.channel().remoteAddress() + ", error : " + cause);

        ServerConnectionGroup connectionGroup = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
        if (connectionGroup != null) {
            CrossAgentLinkedControl.closeConnection(ctx);
            logger.error(toMessage("caught exception the connection to agent disconnected. connection : "
                    + ctx.channel().remoteAddress()));
        }

        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, YanQuMessage msg) throws Exception {
        CrossCommandTask cmdWrapper = new CrossCommandTask(ctx, msg);
        if (msg.getCode() == 41807) {
            CrossBaseServer.getTimerExecutorService().execute(cmdWrapper);
        }else if(CommandUtils.isSlowCommand(msg.getCode())) {//慢命令单独线程池
            CrossBaseServer.getSlowCommandExecutor().execute(cmdWrapper);
        }else {
            CrossBaseServer.getServerCommandExecutor().execute(cmdWrapper);
        }
    }

    private String toMessage(String msg) {
        return "[" + handlerName + "] " + msg;
    }
}
